package io.practice;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 图片更换名称
 * @author Administrator
 *
 */
public class PictureUtils {
	
	private static final String JPG = ".jpg";
	private static final String JPEG = ".jpeg";
	private static final String PNG = ".png";
	private static final String BASE_PATH = "F:\\picture\\";
	
	/**
	 * 保存图片
	 * @param file 图片
	 * @return 图片新地址
	 */
	public static String savePicture(File file) {
		// 1.判断图片是否符合要求
		String name = file.getName();
		boolean isRight = name.endsWith(JPG) || name.endsWith(JPEG) || name.endsWith(PNG);
		if (!isRight) {
			throw new IllegalArgumentException("图片的格式不正确，请上传正确格式的图片！");
		}

		// 2处理图片生成新的图片地址
		String newName = System.currentTimeMillis()+name.substring(name.lastIndexOf("."));
		String newPath = BASE_PATH + newName;
		
		// 3.进行图片保存
		BufferedInputStream in = null ;
		BufferedOutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(file));
			out = new BufferedOutputStream(new FileOutputStream(new File(newPath)));
			
			// 复制图片
			int content = in.read();
			while(content != -1) {
				out.write(content);
				content = in.read();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return newPath;
	}
	
	
	public static void main(String[] args) {
		File file = new File("F:\\1.jpg");
		String path = PictureUtils.savePicture(file);
		System.out.println(path);
	}
	
	
	
}
